package com.gitee.feizns.web.utils;

import com.gitee.feizns.bean.PropertyUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.Map;

/**
 * RestTemplate.
 * @author feizns
 * @since 2019/7/14
 */
public abstract class RestUtils {

    /**
     * 表单参数
     * @param obj
     * @return
     */
    public static final MultiValueMap<String, String> createParams(Object obj) {
        MultiValueMap<String, String> ret = new LinkedMultiValueMap<>();
        if ( obj instanceof Map ) {
            ((Map<String, String>) obj).forEach(ret::add);
        } else {
            PropertyUtils.rwProps(obj).forEach(item -> {
                Object val = item.val();
                ret.add(item.name(), val != null ? val.toString() : null);
            });
        }
        return ret;
    }

    /**
     * 表单请求
     * @param obj
     * @return
     */
    public static HttpEntity<MultiValueMap<String, String>> formReq(Object obj) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> params = RestUtils.createParams(obj);
        HttpEntity request = new HttpEntity<>(params, headers);
        return request;
    }

}
